<?php

function render_partial($name)
{
	include("conf/routes.php");
    include("app/views/partials/".$name.".php");
}

function link_to_css($name)
{
   return("/static/css/".$name.".css");
}

class BaseController
{
    function __construct()
    {
        session_start();
    }
    
    function clear_session()
    {
        $_SESSION = array();
        //session_destroy();
    }
    
    function session_set($key, $value)
    {
        $_SESSION[$key] = $value;
    }
    
    function session_get($key, $default)
    {
        if (isset($_SESSION[$key]))
        {
            return $_SESSION[$key];
        }
        else
        {
            return $default;
        }
    }
    
    function render_view($view_name, $params)
    {
		include("conf/routes.php");
        require_once "app/views/".$params['controller']."/".$view_name.".php";
    }
    
    function render_error($http_status, $message, $context_map)
    {
        include("static/html/".$http_status.".php");
    }
    
    function redirect_to($url)
    {
        header("Location: $url");
        exit;
    }
    
    //set le cookie de session aux valeurs correctes, renvoie true si la connexion a réussi, false si elle a échoué ( mauvais couple user/password)
    function authenticate($username, $password)
    {
        include("lib/config.php");
        mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 
        mysql_select_db($db_name) or die(mysql_error()); 
        
        $data = mysql_query("SELECT * FROM Users WHERE Users.name='".mysql_real_escape_string($username)."'") or die(mysql_error()); 
        
        while($info = mysql_fetch_array( $data )) 
        { 
            if($info['password_hash'] == hash("sha512", $username.$password))
            {  // We got a correct user/password couple. Registering in database + session
                $connexionId = $this->getConnexionId();
                $this->clear_session();
                $this->session_set("connexionId", $connexionId);                
                mysql_query(sprintf("INSERT INTO LoggedUsers (id_connexion, id_user, date_started) VALUES (%d, %d , LOCALTIMESTAMP())", $connexionId, (int)$info['id_user'])) or die(mysql_error());
                return true;
            }            
        }
        
        $this->clear_session();
        return false;
    }
    
    function getConnexionId()
    {        
        include("lib/config.php");
        while(true){
            $random_number = mt_rand(1, 65535);
            mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 
            mysql_select_db($db_name) or die(mysql_error()); 
            $data = mysql_query(sprintf("SELECT * FROM LoggedUsers WHERE LoggedUsers.id_connexion=%d", $random_number)) or die(mysql_error()); 
            
            if( !mysql_fetch_array( $data )){ //There's no previous record with the same number
                return $random_number;
            }            
        }
    }
    
    //regarde le cookie, renvoie l’id utilisateur s’il est connecté, -1 s’il n’est pas connecté
    function isConnected()
    {
        include("lib/config.php");
        $connexionId = $this->session_get("connexionId", NULL);
        if($connexionId == NULL)
        { // User does not have connexionId cookie session
            return -1;
        }
        
        mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 
        mysql_select_db($db_name) or die(mysql_error());
        $data = mysql_query("SELECT * FROM LoggedUsers WHERE id_connexion='".mysql_real_escape_string($connexionId)."'") or die(mysql_error()); 
        
        while($info = mysql_fetch_array( $data )) 
        { 
            if($info["id_connexion"] == $connexionId )
            {  // We got a correct connexion. Check date.                
                $date_begin_con = $info['date_started'];
                
                $sqlReq = "SELECT TIMESTAMPDIFF(MINUTE,'". $date_begin_con."' , LOCALTIMESTAMP());";
                $dateData = mysql_query($sqlReq);
                $diff = mysql_fetch_array($dateData);
                                
                if( $diff['0'] > $session_timeout )
                { // Session timed-out
                    $this->clear_session();
                    return -1;
                }
                return (int)$info['id_user'];
            }            
        }
        return -1;
    }
    
    function isAdmin(){
        $userId = $this->isConnected();
        if( $userId > 0 ){
            include("lib/config.php");
            mysql_connect($db_server, $db_user, $db_password) or die(mysql_error()); 
            mysql_select_db($db_name) or die(mysql_error());
            $data = mysql_query(sprintf("SELECT * FROM Users WHERE id_user=%d",$userId)) or die(mysql_error());
            
            $info = mysql_fetch_array($data);
            
            if($info['is_admin']){
                return true;
            } else {
                return false;
            }
        }
        
        return false;
    }

    function logOut(){
       $this->clear_session();
    }
    
}

?>
